package com.example.tms.controller;

import com.example.tms.bean.*;
import com.example.tms.mapper.*;
import com.example.tms.tools.GlobalParam;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import com.example.tms.annotation.*;
/**
 * 用户信息
 */
@RestController
public class UserController {

    private final UserMapper userMapper;
    private final UserVMapper userVMapper;
    private final PermsVMapper permsVMapper;
    private final UserRoleMapper userRoleMapper;
    private final DriverVMapper driverVMapper;
    private final DriverAMapper driverAMapper;
    private final FileMapper fileMapper;


    @Autowired
    public UserController(UserMapper userMapper, UserVMapper userVMapper, PermsVMapper permsVMapper, UserRoleMapper userRoleMapper, DriverVMapper driverVMapper, DriverAMapper driverAMapper, FileMapper fileMapper) {
        this.userMapper = userMapper;
        this.userVMapper = userVMapper;
        this.permsVMapper = permsVMapper;
        this.userRoleMapper = userRoleMapper;
        this.driverVMapper = driverVMapper;
        this.driverAMapper = driverAMapper;
        this.fileMapper = fileMapper;
    }

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    //查询个人权限
    @RequestMapping(value = "permission",method = RequestMethod.GET)
    public ReturnInfo getUserPerms(){
        Subject subject = SecurityUtils.getSubject();
        UserView userView = (UserView) subject.getPrincipal();
        System.out.println("查询个人权限");
        return ReturnInfo.info2(userView.getPermsList());
    }

    //查询用户信息(用户名)
    @RequestMapping(value = "/user/yhm/{yhm}",method = RequestMethod.GET)
    public UserInfo getUserInfoByYhm(@PathVariable String yhm){
        return userMapper.findByYhm(yhm);
    }

    //查询用户信息(用户id)
    @RequiresPermissions("511")
    @RequestMapping(value = "user/{yhid}",method = RequestMethod.GET)
    public UserView getUserInfo(@PathVariable String yhid){
        return userVMapper.findByYhid(yhid);
    }

    //查询当前用户信息
    @RequestMapping(value = "currentUser",method = RequestMethod.GET)
    public UserView getCurrentUser(){
        Subject subject = SecurityUtils.getSubject();
        return (UserView) subject.getPrincipal();
    }

    //查询当前用户信息
    @RequestMapping(value = "currentUserInfo",method = RequestMethod.GET)
    public UserInfo getCurrentUserInfo(){
        Subject subject = SecurityUtils.getSubject();
        UserView userView = (UserView) subject.getPrincipal();
        UserInfo userInfo =userMapper.findByYhid(userView.getYhid());
        return userInfo;
    }

    //查询当前用户的车牌号信息
    @RequestMapping(value = "currentDriverCph",method = RequestMethod.GET)
    public String getCurrentDriver(){
        String cph;
        Subject subject = SecurityUtils.getSubject();
        UserView userView = (UserView) subject.getPrincipal();
        if(driverVMapper.findBySfzhAndSfcz(userView.getYhm(),true)!=null){
            DriverView driverView = driverVMapper.findBySfzhAndSfcz(userView.getYhm(),true);
            cph = driverView.getCph();
        }else {
            cph="不是司机账户";
        }
        return cph;
    }

    //查询当前用户的司机信息
    @RequestMapping(value = "currentDriver",method = RequestMethod.GET)
    public Object getCurrentDriverNjrq(){
        Subject subject = SecurityUtils.getSubject();
        UserView userView = (UserView) subject.getPrincipal();
        if(driverVMapper.findBySfzhAndSfcz(userView.getYhm(),true)!=null){
            DriverView driverView = driverVMapper.findBySfzhAndSfcz(userView.getYhm(),true);
            return driverView;
        }else {
            return ReturnInfo.info1("不是司机账户");
        }

    }

    //查询当前用户的司机信息
    @RequestMapping(value = "currentDriverApp",method = RequestMethod.GET)
    public Object getCurrentDriverApp(){
        Subject subject = SecurityUtils.getSubject();
        UserView userView = (UserView) subject.getPrincipal();
        if (driverAMapper.findBySfzhandsfcz(userView.getYhm()).size()>0){
            List<DriverApp> driverApps = driverAMapper.findBySfzhandsfcz(userView.getYhm());
            DriverApp driverApp = driverApps.get(0);
            return driverApp;
        }else {
            return ReturnInfo.info1("不是司机账户");
        }

    }

    //查询用户信息列表
    @RequiresPermissions("511")
    @RequestMapping(value = "user",method = RequestMethod.GET)
    public ReturnInfo getUserInfoAll(@RequestParam(required = false, defaultValue = "") String yhm,
                                     @RequestParam(required = false, defaultValue = "") String zsxm,
                                     @RequestParam(required = false, defaultValue = "") String name){
        List<UserView> result = userVMapper.findAll((Root<UserView> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            if(!yhm.equals("")){
                list.add(criteriaBuilder.like(root.get("yhm").as(String.class),"%" + yhm + "%"));
            }
            if(!zsxm.equals("")){
                list.add(criteriaBuilder.like(root.get("zsxm").as(String.class),"%" + zsxm + "%"));
            }
            if(!name.equals("")){
                list.add(criteriaBuilder.like(root.get("name").as(String.class),"%" + name + "%"));
            }
            list.add(criteriaBuilder.equal(root.get("sfcz").as(Boolean.class),true));
            Predicate[] p = new Predicate[list.size()];
            criteriaQuery.where(criteriaBuilder.and(list.toArray(p)));
            criteriaQuery.orderBy(criteriaBuilder.desc(root.get("lasttime")));
            return criteriaQuery.getRestriction();
        });
        return ReturnInfo.info2(result);
    }

    //新建用户信息
    @MonitorRequest
    @RequiresPermissions("512")
    @RequestMapping(value = "user",method = RequestMethod.POST)
    public List<Map<String,Object>> saveUserInfo(@RequestBody UserInfo userInfo) throws NoSuchAlgorithmException {
        List<Map<String,Object>>  list = new ArrayList<>();
        Map<String,Object>  map = new HashMap<>();
        if(userInfo.getYhm().equals("")){
            map.put("yhm", "0");
        }else if(userMapper.findByYhm(userInfo.getYhm())!=null){
            map.put("yhm", "2");//用户名已存在
        }
        if(userInfo.getZsxm().equals("")||!checkName(userInfo.getZsxm())){
            map.put("zsxm", "0");
        }
        if(userInfo.getSjh().equals("")||!checkSjh(userInfo.getSjh())){
            map.put("sjh", "0");
        }else if(userMapper.findBySjh(userInfo.getSjh())!=null){
            map.put("sjh", "2");//手机号已存在
        }
        if(userInfo.getBumenid()==null){
            map.put("bumenid", "0");
        }
        list.add(map);
        if(map.isEmpty()){
            userInfo.setShzt("审核通过");
            userInfo.setZcsj(GlobalParam.getTime());
            userInfo.setLasttime(GlobalParam.getTime());
            userInfo.setSfcz(true);
//            String sj = userInfo.getSjh();//密码设为手机后六位
//
//            if(userInfo.getMima() == null || userInfo.getMima().equals("")){
//
//                userInfo.setMima(GlobalParam.getMD5(sj.substring(sj.length()-6, sj.length())));
//            }
            userInfo.setMima(GlobalParam.getMD5("123456"));
            userMapper.save(userInfo);
            logger.info("新建用户"+userInfo.toString());
        }
        return list;
    }

    //更新用户信息
    @MonitorRequest
    @RequiresPermissions("513")
    @RequestMapping(value = "user",method = RequestMethod.PUT)
    public List<Map<String,Object>> updateUserInfo(@RequestBody UserInfo userInfo) throws NoSuchAlgorithmException {
        List<Map<String,Object>>  list = new ArrayList<>();
        Map<String,Object>  map = new HashMap<>();
        if(userInfo.getYhid().equals("")||userMapper.findByYhid(userInfo.getYhid())==null){
            map.put("yhid", "0");//该用户不存在
        }
        UserInfo olduser = userMapper.findByYhid(userInfo.getYhid());
        if(!userInfo.getYhm().equals(olduser.getYhm())&&userMapper.findByYhm(userInfo.getYhm())!=null) {
            map.put("yhm", "2");//用户名已存在
        }else if(userInfo.getYhm().equals("")){
            map.put("yhm", "0");
        }
        if(userInfo.getZsxm().equals("")||!checkName(userInfo.getZsxm())){
            map.put("zsxm", "0");
        }
        if(userInfo.getSjh().equals("")||!checkSjh(userInfo.getSjh())){
            map.put("sjh", "0");
        }
        if(userInfo.getBumenid()==null){
            map.put("bumenid", "0");
        }
        list.add(map);
        if(map.isEmpty()){
            userInfo.setZcsj(userMapper.findByYhid(userInfo.getYhid()).getZcsj());
            userInfo.setLasttime(GlobalParam.getTime());
            userInfo.setSfcz(true);
//            String sj = userInfo.getSjh();//密码设为手机后六位
//            if(userInfo.getMima() == null || userInfo.getMima().equals("")){
//                userInfo.setMima(GlobalParam.getMD5( sj.substring(sj.length()-6, sj.length())));
//            }
            userMapper.saveAndFlush(userInfo);
            logger.info("更新用户"+userInfo.toString());
        }
        return list;
    }

    //删除用户信息（假删除 用户id）
    @MonitorRequest
    @RequiresPermissions("514")
    @RequestMapping(value = "user/{yhid}",method = RequestMethod.DELETE)
    public ReturnInfo deleteUserinfo(@PathVariable String yhid){
        String b;
        if(yhid==null||userMapper.findByYhid(yhid)==null){
            b = "该用户不存在！";
        }else{
            userMapper.DeleteByYhid(yhid);
            userRoleMapper.deleteByYhid(yhid);
            b = "删除成功！";
            logger.info("删除用户"+yhid);
        }
        return ReturnInfo.info1(b);
    }

    //上传头像
    @RequestMapping(value = "/headpicup",method = RequestMethod.PUT)
    public ReturnInfo upheadPic(@RequestBody UserInfo userInfo) {
       String msg;
        if(userInfo.getYhid().equals("")||userMapper.findByYhid(userInfo.getYhid())==null){
           msg = "用户不存在！";
        }else if(userInfo.getHeadpic().equals("")){
            msg = "头像上传失败不存在！";
        }else {
            UserInfo userInfo1 = userMapper.findByYhid(userInfo.getYhid());
            userInfo1.setHeadpic(userInfo.getHeadpic());
            userMapper.saveAndFlush(userInfo1);
            FileInfo fileInfo = fileMapper.findByFileid(userInfo.getHeadpic());
            fileInfo.setSfcz(true);
            fileMapper.saveAndFlush(fileInfo);
            msg = "上传成功！";
        }
        return ReturnInfo.info1(msg);
    }

    //修改密码
    @MonitorRequest
    @RequestMapping(value = "/mima",method = RequestMethod.PUT)
    public ReturnInfo updateMima(@RequestBody UserInfo modifyPsw) throws NoSuchAlgorithmException {
        String b;
        UserInfo olduser = userMapper.findByYhid(modifyPsw.getYhid());
        if(!GlobalParam.getMD5(modifyPsw.getOldpsw()).equals(olduser.getMima())) {
            b = "旧密码错误！";
        }
        else if(modifyPsw.getYhid().equals("")||userMapper.findByYhid(modifyPsw.getYhid())==null){
            b = "该用户名不存在!";
        }else if (modifyPsw.getMima()==null||!checkPsw(modifyPsw.getMima())) {
            b = "密码格式错误!";
        }else {
            userMapper.UpdateMima(modifyPsw.getYhid(),GlobalParam.getMD5(modifyPsw.getMima()));
            b = "密码修改成功!";
        }
        return ReturnInfo.info1(b);
    }


    //修改密码（app端忘记密码）
    @MonitorRequest
    @RequestMapping(value = "/resetPsw",method = RequestMethod.PUT)
    public ReturnInfo resetMima(@RequestBody UserInfo modifyPsw) throws NoSuchAlgorithmException {
        String b;
        if(modifyPsw.getYhid().equals("")||userMapper.findByYhid(modifyPsw.getYhid())==null){
            b = "该用户名不存在!";
        }else{
            UserInfo userInfo = userMapper.findByYhid(modifyPsw.getYhid());
            DriverView driverView = driverVMapper.findBySfzhAndSfcz(userInfo.getYhm(),true);
            if (modifyPsw.getSjh()==null||modifyPsw.getSjh().equals("")||!modifyPsw.getSjh().equals(driverView.getJsysj())) {
                b = "手机号码格式错误!";
            }else {
                String sj = modifyPsw.getSjh();//密码设为手机后六位
                userMapper.UpdateMima(modifyPsw.getYhid(),GlobalParam.getMD5( sj.substring(sj.length()-6, sj.length())));
                b = "密码修改成功!";
            }
        }
        return ReturnInfo.info1(b);
    }

    //修改密码（web端忘记密码）
    @MonitorRequest
    @RequestMapping(value = "/resetPswWeb",method = RequestMethod.PUT)
    public ReturnInfo resetMimaWeb(@RequestBody JiGuang modifyPsw) throws NoSuchAlgorithmException {
        String b;
        if(modifyPsw.getYhm().equals("")||userMapper.findByYhm(modifyPsw.getYhm()) ==null){
            b = "该用户名不存在!";
        }else{
            UserInfo userInfo = userMapper.findByYhm(modifyPsw.getYhm());
        if (modifyPsw.getMobile()==null||modifyPsw.getMobile().equals("")||userMapper.findBySjh(modifyPsw.getMobile())==null||!modifyPsw.getMobile().equals(userInfo.getSjh())) {
           logger.info("modifyPsw.getSjh():"+modifyPsw.getMobile()+"userInfo.getSjh():"+userInfo.getSjh());
            b = "手机号码格式错误!";
        }else {
            UserInfo userInfo1  = userMapper.findByYhm(modifyPsw.getYhm());
            String sj = modifyPsw.getMobile();//密码设为手机后六位
            userInfo1.setMima(GlobalParam.getMD5( sj.substring(sj.length()-6, sj.length())));
            userMapper.saveAndFlush(userInfo1);
            b = "密码修改成功!";
         }
        }
        return ReturnInfo.info1(b);
    }

    //检查手机号码格式
    private Boolean checkSjh(String sjh){
        Boolean b = false;
        if(sjh.matches("^1[0-9 ]{10,12}$")){
            b = true;
        }
        return b;
    }

    //检查真实姓名格式
    private Boolean checkName(String  zsxm){
        Boolean b = false;
        if(zsxm.matches("^[\\u4E00-\\u9FA5A-Za-z]+$")){
            b = true;
        }
        return b;
    }
    //检查密码格式
    private Boolean checkPsw(String  mima){
        Boolean b = false;
        if(mima.matches("^[0-9a-zA-Z]{6,12}$")){
            b = true;
        }
        return b;
    }
}
